package com.huazai.apply.manager.web.action;


import com.huazai.apply.manager.bean.ApplyMessage;
import com.huazai.apply.manager.bean.User;
import com.huazai.apply.manager.dao.ApplyMapper;
import com.huazai.apply.manager.utils.IdUtil;
import com.huazai.apply.manager.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author EZTTU
 */
@WebServlet(name = "Apply", value = {"/add", "/decide", "/delete"})
public class ApplyServlet extends HttpServlet {
    private static final String SERVICE_ADD = "/add";
    private static final String SERVICE_DECIDE = "/decide";
    private static final String SERVICE_DELETE = "/delete";
    private static final String RESULT_PRE = "Prepared";


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String servletPath = request.getServletPath();
        HttpSession session = request.getSession(false);
        User userMessage = (User) session.getAttribute("UserMessage");

        if (userMessage.getUserField().equals("admin")) {
            if (servletPath.equals(SERVICE_DECIDE)) {
                this.doDecide(request, response);
            } else if (servletPath.equals(SERVICE_DELETE)) {
                this.doDelete(request, response);
            } else {
                response.sendRedirect(request.getContextPath());
            }

        } else {
            if (servletPath.equals(SERVICE_ADD)) {
                try {
                    this.doAdd(request, response);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else if (servletPath.equals(SERVICE_DELETE)) {
                this.doDelete(request, response);
            } else {
                response.sendRedirect(request.getContextPath());
            }

        }

    }

    private void doAdd(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();

        //0012-12-12T20:12,注意前端的传入数据是这样子的，所以需要以下的语句来进行修正
        //replaceTime用于解决时间格式不匹配而出此下策。
        String userid = request.getParameter("userid");
        String dateTime = request.getParameter("dateTime");
        String wantTime = request.getParameter("outTime");
        String replaceTime = dateTime.replace("T", " ");
        replaceTime += ":00";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
        Date date = sdf.parse(replaceTime);

        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            ApplyMapper mapper = sqlSession.getMapper(ApplyMapper.class);
            ApplyMessage applyMessage =
                    new ApplyMessage(userid, date, RESULT_PRE, Integer.parseInt(wantTime),
                            new IdUtil(1, 1, 1).nextId());

            boolean insertResult = mapper.uploadApply(applyMessage);
            if (insertResult) {
                sqlSession.commit();
                pw.print("<h1 align=\"center\">申请提交成功</h1>");
            } else {
                sqlSession.rollback();
                pw.print("<h1 align=\"center\">申请提交失败</h1>");
            }

        }

    }


    private void doDecide(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        String applyId = request.getParameter("applyID");
        String result = request.getParameter("result");
        Map<String, String> map = new HashMap<>();
        map.put("result", result);
        map.put("applyId", applyId);

        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            ApplyMapper mapper = sqlSession.getMapper(ApplyMapper.class);
            boolean b = mapper.judgeApply(map);
            if (b) {
                sqlSession.commit();
                response.sendRedirect(request.getContextPath() + "/admin");
            } else {
                sqlSession.rollback();
                pw.print("<h1 align=\"center\">审批失败</h1>");
                pw.print("<a href='javascript:void(0)' onclick='window.history.back()'>返回上一级</a>");
            }
        }

    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String applyId = request.getParameter("applyID");
        HttpSession session = request.getSession();
        User userMessage = (User) session.getAttribute("UserMessage");

        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            ApplyMapper mapper = sqlSession.getMapper(ApplyMapper.class);
            boolean b = mapper.deleteApply(applyId);
            if (b) {
                sqlSession.commit();
                if (userMessage.getUserField().equals("admin")) {
                    response.sendRedirect(request.getContextPath() + "/admin");
                } else {
                    response.sendRedirect(request.getContextPath() + "/user");
                }
            } else {
                sqlSession.rollback();
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter pw = response.getWriter();
                pw.print("<h1 align='center'>出校申请删除失败</h1>");
                pw.print("<a href='javascript:void(0)' onclick='window.history.back()'>返回上一级</a>");
            }
        }
    }

}
